package com.tian.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.tian.common.util.RabbitMQConstant;
import com.tian.mq.message.ChargingOrderMessage;
import com.tian.service.station.ChargingOrderStatusService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * {@code @description:} 充电订单状态变更消费者
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-10-25 15:19
 * {@code @version:} 1.0
 */
@RabbitListener(queues = RabbitMQConstant.CHARGING_ORDER_STATUS_CHANGE_QUEUE)
@Component
@Slf4j
public class ChargingOrderStatusConsumer {

    @Resource
    private ChargingOrderStatusService stationGunCommunicateLogService;
    @RabbitHandler
    public void process(Object data, Channel channel, Message message) throws IOException {
        log.info("充电订单状态变更消费者收到消息，开始处理");
        ChargingOrderMessage chargingOrderMessage = JSON.parseObject(new String(message.getBody()), ChargingOrderMessage.class);
        if (chargingOrderMessage == null) {
            log.info("站枪通信日志消费者收到消息,消息内容：{}", message.getBody());
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            return;
        }

        log.info("站枪通信日志消费者收到消息,消息内容：{}", chargingOrderMessage);

        try {
            boolean save = stationGunCommunicateLogService.updateChargingOrderStatus(chargingOrderMessage);
            if (save) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);     // 重新入队
            }
        }catch (Exception e) {
            log.error("充电订单状态变更消费者处理失败", e);
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }
        log.info("充电订单状态变更消费者处理完成");
    }
}
